package com.atguigu.tingshu.search.runnable;

import com.atguigu.tingshu.search.factory.ScheduleTaskThreadPoolFactory;
import com.atguigu.tingshu.search.service.impl.ItemServiceImpl;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;


public class RebuildBloomFilterRunnable implements Runnable{
    Logger logger = LoggerFactory.getLogger(this.getClass());


    private RedissonClient redissonClient;
    private StringRedisTemplate redisTemplate;
    private ItemServiceImpl itemServiceImpl;

    public RebuildBloomFilterRunnable(RedissonClient redissonClient, StringRedisTemplate redisTemplate,ItemServiceImpl itemServiceImpl) {
        this.itemServiceImpl = itemServiceImpl;
        this.redissonClient = redissonClient;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void run() {
        RBloomFilter<Object> albumIdBloomFilterNew = redissonClient.getBloomFilter("albumIdBloomFilterNew");
        albumIdBloomFilterNew.tryInit(1000000l, 0.001);

        List<Long> albumInfoIdList = itemServiceImpl.getAlbumInfoIdList();
        for (Long albumId : albumInfoIdList) {
            albumIdBloomFilterNew.add(albumId);
        }

        //rename key key1 用key1的名字换key的名字
        String script = " redis.call(\"del\",KEYS[1])" +
                "  redis.call(\"del\",KEYS[2])" +
                "  redis.call(\"rename\",KEYS[3],KEYS[1])" +
                "  redis.call(\"rename\",KEYS[4],KEYS[2]) return 0";
        List<String> asList = Arrays.asList("albumIdBloomFilter", "{albumIdBloomFilter}:config", "albumIdBloomFilterNew", "{albumIdBloomFilterNew}:config");
        Long execute = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), asList);
        if (execute == 0){
            logger.info("老布隆已经被删除，新布隆上线。。。");
        }


//        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);
//        scheduledExecutorService.schedule(this,10, TimeUnit.DAYS);  //延时任务+ 嵌套任务本身 从而实现定时的效果  [nacos源码]
        ScheduleTaskThreadPoolFactory instance = ScheduleTaskThreadPoolFactory.getInstance();
        instance.execute(this,10l,TimeUnit.SECONDS); //测试使用
//        instance.execute(this,7l,TimeUnit.DAYS);//线上

    }
}
